package middle;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Solution_49 {

    public List<List<String>> groupAnagrams(String[] strs) {
        Set<Integer> existedLength = new HashSet<>();
        List<int[]> existed = new ArrayList<>();
        List<List<String>> rst = new ArrayList<>();
        for (String str : strs) {
            int[] chars = new int[26];
            for (int i = 0; i < str.length(); i++) {
                chars[str.charAt(i) - 'a']++;
            }

            int existIndex = -1;
            for (int i = 0; i < existed.size() && existedLength.contains(str.length()); i++) {
                int[] compare = existed.get(i);
                boolean exist = true;
                for (int j = 0; j < chars.length; j++) {
                    if (compare[j] != chars[j]) {
                        exist = false;
                        break;
                    }
                }
                if (exist) {
                    existIndex = i;
                    break;
                }
            }
            List<String> list;
            if (existIndex >= 0) {
                list = rst.get(existIndex);
            } else {
                existed.add(chars);
                existedLength.add(str.length());
                list = new ArrayList<>();
                rst.add(list);
            }
            list.add(str);
        }
        return rst;
    }

    public static void main(String[] args) {
        Solution_49 model = new Solution_49();
        List<List<String>> lists = model.groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"});
        for (List<String> list : lists) {
            System.out.println(list);
        }
    }
}
